import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 马拉圈
 * Date: 2023-04-05
 * Time: 11:16
 */
public class TCPEchoClient {
    Socket socket = null;//此socket对象代表了服务器的socket文件~

    public TCPEchoClient(String host, int port) throws IOException {
        this.socket = new Socket(host, port);
        //这个过程客户端主动连接了服务器，这样就可以被服务器的accept接受~
        //而服务器的accept返回的对象，默认填上了客户端的IP与端口号
    }

    public void start() {
        Scanner scanner = new Scanner(System.in);
        try (InputStream inputStream = socket.getInputStream();
             OutputStream outputStream = socket.getOutputStream()){
            PrintWriter printWriter = new PrintWriter(outputStream);
            Scanner scannerFromServer = new Scanner(inputStream);
            while(true) {
                System.out.print("-> ");
                String request = scanner.nextLine();
                printWriter.println(request);
                printWriter.flush();
                String response = scannerFromServer.next();//如果为空，则需要等待对方flush
                System.out.printf("[%s : %d] 收到请求：%s， 返回响应：%s\n", socket.getInetAddress().toString(),
                        socket.getPort(), request, response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        TCPEchoClient tcpEchoClient = new TCPEchoClient("10.61.10.239", 9090);
        tcpEchoClient.start();
    }
}
